<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    function ajax ({
      method,
      url,
      params,
      done
    }) {
      let xhr = new XMLHttpRequest()
      method = method.toUpperCase() // 转为大写
      let dataSrc = []
      for (let key in params) {
        dataSrc.push(key + '=' + params[key])
      }
      dataSrc = dataSrc.join('&')// 拼接字符串
      if (method === 'GET') {
        xhr.open(method, url + '?' + dataSrc)
        xhr.send()
      } else if (method === 'POST') {
        xhr.open(method, url)
        xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
        xhr.send(dataSrc)
      }
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            done(JSON.parse(xhr.responseText))
          }
        }
      }
    }
    // ajax({
    //   method: 'get',
    //   url: 'http://localhost:3000/api/getuser',
    //   params: {
    //     name: '方现伟',
    //     age: '20岁'
    //   },
    //   done: function (params) {
    //     console.log(params);
    //   }
    // })
    ajax({
      method: 'post',
      url: 'http://localhost:3000/api/addUser',
      params: {
        name: '方现伟',
        age: '20岁'
      },
      done: function (params) {
        console.log(params);
      }
    })
    ajax({
      method: 'get',
      url: 'http://localhost:3000/api/userlist',
      params: {

      },
      done: function (params) {
        console.log(params);
      }
    })
  </script>
</body>

</html>